﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace TaskBasedSchedule.Core
{
    public class DatabaseFactory
    {
        #region Fields
        private string _msSqlConnectionString;
        #endregion

        #region Consturctor&Destructor

        public DatabaseFactory()
        {
            PrivateInitialize();
        }

        #endregion

        #region Properties

        public DatabaseType WorkingDatabaseType
        {
            //TODO: Support more database.
            get { return DatabaseType.MsSql; }
        }

        #endregion

        #region Public Functions

        public Database GetDatabase(DatabaseType type = DatabaseType.MsSql)
        {
            switch (type)
            {
                case DatabaseType.MySql:
                    return PrivateCreateMsSqlDatabase();
                default:
                    throw new InvalidOperationException(string.Format("Target database type `{0}` is not supported.", type.ToString()));
            }
        }

        #endregion

        #region Private Functions

        public void PrivateInitialize()
        {
            //Load settings from configuration.
            _msSqlConnectionString = ConfigurationManager.AppSettings["mssql_connection"];

        }

        private Database PrivateCreateMsSqlDatabase()
        {
            if (string.IsNullOrEmpty(_msSqlConnectionString))
                throw new InvalidOperationException("Invalid connection configuration.");

            SqlConnection mssqlCoon = new SqlConnection();
            mssqlCoon.ConnectionString = _msSqlConnectionString;

            try
            {
                mssqlCoon.Open();
                return new Database(DatabaseType.MsSql, mssqlCoon);
            }catch(Exception ex)
            {
                throw new DatabaseOperationException(ex);
            }
        }

        #endregion
    }
}